#!/usr/bin/env guile
!#

(use-modules (ice-9 binary-ports)
             (rnrs bytevectors)
             (ice-9 match)
             (system vm elf)
             (charting)
             (srfi srfi-1))

(define (read-elf file)
  (parse-elf (call-with-input-file file
               (lambda (port) (get-bytevector-all port)))))

(define (make-elf-map elf-file png-file)
  (let ((elf (read-elf elf-file)))
    (make-page-map
     elf-file
     (stable-sort
      (filter-map
       (match-lambda
        ((name . section)
         (and (not (eqv? (elf-section-type section) SHT_NULL))
              (cons (if (string-null? name)
                        "(unnamed)"
                        name)
                    (cons (elf-section-offset section)
                          (elf-section-size section))))))
       (elf-sections-by-name elf))
      (match-lambda*
       (((_ . (x-start . _)) (_ . (y-start . _)))
        (<= x-start y-start))))
     png-file)))

(when (batch-mode?)
  (match (program-arguments)
    ((_ elf-file png-file)
     (make-elf-map elf-file png-file))
    ((arg0 . _)
     (format (current-error-port) "Usage: ~a ELF-FILE PNG-FILE\n" arg0)
     (exit 1))))
